package com.example.springboot_bakend.service;

import com.example.springboot_bakend.dto.LoginRequest;
import com.example.springboot_bakend.dto.RegisterRequest;
import com.example.springboot_bakend.dto.UserResponse;
import com.example.springboot_bakend.entity.User;
import com.example.springboot_bakend.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserRepository userRepository;
    
    @Transactional
    public UserResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (request.getEmail() != null && userRepository.existsByEmail(request.getEmail())) {
            throw new RuntimeException("邮箱已被使用");
        }
        
        // 检查钱包地址是否已存在
        if (request.getWalletAddress() != null && !request.getWalletAddress().isEmpty() 
            && userRepository.existsByWalletAddress(request.getWalletAddress())) {
            throw new RuntimeException("钱包地址已被绑定");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword()); // 在生产环境中应该加密密码
        user.setEmail(request.getEmail());
        user.setWalletAddress(request.getWalletAddress());
        
        User savedUser = userRepository.save(user);
        
        return convertToResponse(savedUser);
    }
    
    public UserResponse login(LoginRequest request) {
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名或密码错误"));
        
        if (!user.getPassword().equals(request.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        return convertToResponse(user);
    }
    
    public UserResponse getUserById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToResponse(user);
    }
    
    public UserResponse getUserByUsername(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToResponse(user);
    }
    
    public UserResponse getUserByWalletAddress(String walletAddress) {
        User user = userRepository.findByWalletAddress(walletAddress)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToResponse(user);
    }
    
    @Transactional
    public UserResponse updateWalletAddress(Long userId, String walletAddress) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 检查钱包地址是否已被其他用户使用
        if (walletAddress != null && !walletAddress.isEmpty()) {
            Optional<User> existingUser = userRepository.findByWalletAddress(walletAddress);
            if (existingUser.isPresent() && !existingUser.get().getId().equals(userId)) {
                throw new RuntimeException("钱包地址已被其他用户绑定");
            }
        }
        
        user.setWalletAddress(walletAddress);
        User updatedUser = userRepository.save(user);
        
        return convertToResponse(updatedUser);
    }
    
    public List<UserResponse> getAllUsers() {
        return userRepository.findAll().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    private UserResponse convertToResponse(User user) {
        UserResponse response = new UserResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setEmail(user.getEmail());
        response.setWalletAddress(user.getWalletAddress());
        response.setCreatedAt(user.getCreatedAt());
        return response;
    }
}

